//
//  YSPwdView.m
//  Yueshi
//
//  Created by Northwan on 16/4/12.
//  Copyright © 2016年 悦食中国. All rights reserved.
//  验证码控件

#import "YSPwdView.h"

@interface YSPwdView()<YSTextFieldDelegate>
@property (strong, nonatomic) NSMutableArray *pwdTextArr;
@end
@implementation YSPwdView

-(NSMutableArray *)pwdTextArr{
    if (!_pwdTextArr) {
        _pwdTextArr = [NSMutableArray arrayWithCapacity:6];
    }
    return _pwdTextArr;
}

+(instancetype)pwdView{
    return [[[NSBundle mainBundle]loadNibNamed:@"YSPwdView" owner:nil options:nil]lastObject];
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    for(int i = 0;i<self.subviews.count;i++){
        UITextField *tf = self.subviews[i];
        tf.delegate = self;
        tf.tag = i;
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (!ISBLANK(string)) {
        if(!ISBLANK(textField.text) && !ISBLANK(string) && textField.tag != self.subviews.count - 1){
            UITextField *tf =  self.subviews[textField.tag + 1];
            tf.text = string;
            self.pwdTextArr[tf.tag] = string;
            [tf becomeFirstResponder];
        }else{
            if (textField.tag != self.subviews.count - 1){
                [self.subviews[textField.tag + 1] becomeFirstResponder];
                textField.text = string;
                self.pwdTextArr[textField.tag] = string;
            }else if(!ISBLANK(string) && !ISBLANK(textField.text) && ![textField.text isEqualToString:string]){
                NSLog(@"xxx");
            }else{
                textField.text = string;
                self.pwdTextArr[textField.tag] = string;
            }
        }
    }
    else{
        if(!ISBLANK(textField.text) && ISBLANK(string)){
            textField.text = string;
            [self.pwdTextArr removeObjectAtIndex:textField.tag];
        }
    }
    NSLog(@"邀请码: ----%@",[self pwd2Str]);
    return  NO;
}

-(NSMutableString *)pwd2Str{
    NSMutableString *strs = [NSMutableString string];
    for (NSString *str in self.pwdTextArr) {
        [strs appendString:str];
    }
    return strs;
}

-(void)textFieldDidDeleteBackward:(UITextField *)textField{
    NSLog(@"textFieldDidDeleteBackward");
    if(ISBLANK(textField.text) && textField.tag != 0){
        [self.subviews[textField.tag - 1] becomeFirstResponder];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == self.subviews.count - 1 && [[self pwd2Str] length] == 6){
        if ([_delegate respondsToSelector:@selector(inputFinish:)]) {
            [self removeFromSuperview];
            [_delegate inputFinish:[self pwd2Str]];
        }
    }
}

@end
